<template>
	<view class="scrollWrap">
	<!-- 	<view class="donwBox">
			<image src="/static/downBox.png" class="downBoxPng" mode="" @tap="testInit"></image>
		</view> -->
		<view :id="id" class="tabWrap">
			<scroll-view id="tab-bar" enhanced="false" show-scrollbar="false" scroll-bar="false"  class="scroll-h" :scroll-x="true" :scroll-left="scrollLeft" :scroll-with-animation='barFirstTimeMove'>
			    <view v-for="(tab,index) in dataList" :key="tab.id"  :id="'tab-item-' + index" class="tab-item"  @click="ontabtap(index)">
			        <text class="text" :class="[barFirstTimeMove ?  '': 'opacity',currentIndex == index ? 'active':'']">{{tab.name}}</text>
			    </view>
			</scroll-view>
		</view>
	</view> 
</template>
<script>
	export default {
		name:"tab-data",
		props:['dataList'],
		data() {
			return {
				scrollLeft: 0, // 滚动scroll-view的左边滚动距离
				tabQueryInfo: [], // 存放对tab菜单查询后的节点信息
				componentWidth: 0, // 屏幕宽度，单位为px
				scrollBarLeft: 0, // 移动bar需要通过translateX()移动的距离
				parentLeft: 0, // 父元素(tabs组件)到屏幕左边的距离
				id: 'cu-tab', // id值
				currentIndex: 0,
				barFirstTimeMove: false, 
				isAsync: false
			}
		},
		watch: {
		    // 监听tab的变化，重新计算tab菜单的布局信息，因为实际使用中菜单可能是通过
		    // 后台获取的（如新闻app顶部的菜单），获取返回需要一定时间，所以list变化时，重新获取布局信息
		    dataList(n, o) {
		        // list变动时，重制内部索引，否则可能导致超出数组边界的情况
		        if (!this.barFirstTimeMove && n.length !== o.length) {
		            this.currentIndex = 0;
		        }
		        // 用$nextTick等待视图更新完毕后再计算tab的局部信息，否则可能因为tab还没生成就获取，就会有问题
		        this.$nextTick(() => {
		            this.init();
		        });
		    }
		},	
		mounted() {
			// console.log('mounted');
			this.init();
		},	
		methods: {
			testInit() {
				this.init();
			},
			ontabtap(index) {
				if(this.isAsync) return;
				if (index == this.currentIndex) return;
				this.$nextTick(() => {
				    this.currentIndex = index;
					this.$emit('changeTab',index);
				    this.scrollByIndex();
				});
			},
			getRect(selector,all,context) {
				return new Promise(function(resolve) {
					let qurey = uni.createSelectorQuery();
					if (context) {
						qurey = uni.createSelectorQuery().in(context);
					}
					qurey[all ? 'selectAll' : 'select'](selector).boundingClientRect(function(rect) {
						if (all && Array.isArray(rect) && rect.length) {
							resolve(rect);
						}
						if (!all && rect) {
							resolve(rect);
						}
					}).exec();
				});
	        },
			async init() {
			    let tabRect = await this.getRect('#' + this.id, false, this);
			    this.parentLeft = tabRect.left;
			    this.componentWidth = tabRect.width;
			    this.getTabRect();
			},
			scrollByIndex() {
				// console.log('this.tabQueryInfo',this.tabQueryInfo);
			    let tabInfo = this.tabQueryInfo[this.currentIndex];
			    if (!tabInfo) return;
			    let tabWidth = tabInfo.width;
			    let offsetLeft = tabInfo.left - this.parentLeft;
			    let scrollLeft = offsetLeft - (this.componentWidth - tabWidth) / 2;
			    this.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft;
			    if (this.barFirstTimeMove == false) {
			        setTimeout(() => {
			            this.barFirstTimeMove = true;
			        }, 100)
			    }
			},
			getTabRect() {
			    // 创建节点查询
			    let query = uni.createSelectorQuery().in(this);
			    for (let i = 0; i < this.dataList.length; i++) {
			        query.select(`#tab-item-${i}`).fields({
			            size: true,
			            rect: true
			        });
			    }
			    query.exec(
			        function(res) {
			            this.tabQueryInfo = res;
			     
			            this.scrollByIndex();
			        }.bind(this)
			    );
			}
		}
	}
</script>

<style lang="scss">
::-webkit-scrollbar,
::-webkit-scrollbar,
::-webkit-scrollbar {
	display: none;
	width: 0 !important;
	height: 0 !important;
	-webkit-appearance: none;
	background: transparent;
}
	
.scrollWrap {
	   width: 750rpx;
	   position: relative;
	   margin-bottom: 20rpx;
	    .tabWrap {
			height: 88rpx;
		}
	   .scroll-h {
			width: 750rpx;
			height: 88rpx;
			overflow-x: auto;
			flex-direction: row;
			white-space: nowrap;
			&::-webkit-scrollbar {
				  display:none;
				  width:0;
				  height:0;
				  color:transparent;
				}
			// background-color: #fff;
			.tab-item {
				    display: inline-block;
					height: 85rpx;
				    flex-wrap: nowrap;
					font-size: 30rpx;
					// color:#96989a;
				    padding-left: 28rpx;
				    padding-right: 28rpx;
					box-sizing: border-box;
					position: relative;
					.text {
						display: block;
						height: 100%;
						line-height: 88rpx;
						position: relative;
						&.opacity{
							opacity:0
						}
						&.active {
							// background-color:#ec5745;
							color:#3c84f4;
							// border-bottom: 3px solid #ec5745;
							&:after {
								content: '';
								width: 60%;
								height: 6rpx;
								border-radius: 3rpx;
								background-color: #3c84f4;
								left: 20%;
				
								position: absolute;
								z-index: 999;
								bottom: 5rpx;
							}
						}
					}
			}
	   }
	
		flex: none;
		.donwBox {
			width: 80rpx;
			height: 88rpx;
			// background-color: red;
			background-color: #fff;
			position: absolute;
			right: 0rpx;
			top:0rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			.downBoxPng {
				width: 22rpx;
				height: 12rpx;
			}
		}
	}
</style>